package com.eian.boot.module.system.user.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.eian.boot.common.constants.PermissionConstants;
import com.eian.boot.common.core.model.CommonResult;
import com.eian.boot.module.system.associations.user.post.service.UserPostRelationService;
import com.eian.boot.module.system.post.model.dto.UserPostAssignRequest;
import com.eian.boot.module.system.user.model.dto.*;
import com.eian.boot.module.system.user.model.vo.UserDetailVO;
import com.eian.boot.module.system.user.model.vo.UserListVO;
import com.eian.boot.module.system.user.service.SysUserService;
import com.eian.boot.mybatis.core.page.PageResult;
import com.eian.boot.security.utils.SessionHelper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "系统用户接口")
@RestController
@RequestMapping("/system/user")
@AllArgsConstructor
public class UserController {
    private final SysUserService userService;
    private final UserPostRelationService userPostRelationService;

    @Operation(summary = "创建用户")
    @SaCheckPermission(PermissionConstants.User.CREATE)
    @PostMapping("/create")
    public CommonResult<String> create(@Valid @RequestBody CreateUserRequest request) {
        userService.createUser(request);
        return CommonResult.ok("用户创建成功");
    }

    @Operation(summary = "获取用户详情")
    @SaCheckPermission(PermissionConstants.User.QUERY)
    @GetMapping("/detail")
    public CommonResult<UserDetailVO> getDetail(Long userId) {
        if (ObjectUtils.isEmpty(userId)) {
            userId = SessionHelper.getUserId();
        }
        return CommonResult.ok(userService.getUserDetail(userId));
    }

    @Operation(summary = "更新用户基础信息")
    @SaCheckPermission(PermissionConstants.User.UPDATE)
    @PostMapping("/update")
    public CommonResult<String> update(@Valid @RequestBody UserUpdateRequest request) {
        if (ObjectUtils.isEmpty(request.getId())) {
            request.setId(SessionHelper.getUserId());
        }
        userService.updateUser(request);
        return CommonResult.ok();
    }

    @Operation(summary = "分页查询用户列表")
    @SaCheckPermission(PermissionConstants.User.LIST)
    @GetMapping("/list")
    public CommonResult<PageResult<UserListVO>> list(UserQueryRequest request) {
        return CommonResult.ok(userService.getUserList(request));
    }

    @Operation(summary = "重置密码（随机）")
    @SaCheckPermission(PermissionConstants.User.RESET_PWD)
    @PostMapping("/reset-password/{id}")
    public CommonResult<String> resetPassword(@Parameter(description = "用户ID") @PathVariable Long id) {
        // 使用okStr方法确保新密码作为data返回,而不是msg
        return CommonResult.okStr(userService.resetRandomPassword(id));
    }

    @Operation(summary = "更新密码")
    @PostMapping("/update-password")
    public CommonResult<String> updatePassword(@RequestBody UpdatePasswordRequest request) {
        userService.updatePassword(SessionHelper.getUserId(), request.getPassword(), request.getNewPassword());
        return CommonResult.ok();
    }

    @Operation(summary = "删除用户")
    @SaCheckPermission(PermissionConstants.User.DELETE)
    @PostMapping("/delete/{id}")
    public CommonResult<String> delete(@Parameter(description = "用户ID") @PathVariable Long id) {
        userService.deleteUser(id);
        return CommonResult.ok("用户删除成功");
    }

    @Operation(summary = "启用/禁用用户")
    @SaCheckPermission(PermissionConstants.User.STATUS)
    @PostMapping("/update-status")
    public CommonResult<String> updateStatus(@Valid @RequestBody UserStatusUpdateRequest request) {
        userService.updateUserStatus(request.getId(), request.getStatus());
        return CommonResult.ok();
    }

    @Operation(summary = "分配用户角色")
    @SaCheckPermission(PermissionConstants.User.ASSIGN_ROLE)
    @PostMapping("/assign-roles")
    public CommonResult<String> assignRoles(@Valid @RequestBody UserRoleAssignRequest request) {
        userService.assignUserRoles(request.getId(), request.getRoleIds());
        return CommonResult.ok("角色分配成功");
    }

    @Operation(summary = "分配用户岗位")
    @SaCheckPermission(PermissionConstants.User.ASSIGN_POST)
    @PostMapping("/assign-posts")
    public CommonResult<String> assignPosts(@Valid @RequestBody UserPostAssignRequest request) {
        userPostRelationService.assignUserPosts(request.getUserId(), request.getPostIds());
        return CommonResult.ok("岗位分配成功");
    }

    @Operation(summary = "获取用户岗位ID列表")
    @SaCheckPermission(PermissionConstants.User.QUERY)
    @GetMapping("/{id}/posts")
    public CommonResult<List<Long>> getUserPosts(@Parameter(description = "用户ID") @PathVariable Long id) {
        return CommonResult.ok(userPostRelationService.getPostIdsByUserId(id));
    }
}
